/**
 * Created by billy on 2021/2/3.
 */
var _dingdingUrl = "https://oapi.dingtalk.com/robot/send?access_token=c25c30c5ef4ac7bf25eb5b8fc1f8650405526abd097d54d6d7fc7b0aba14f780";
//_dingdingUrl = "https://oapi.dingtalk.com/robot/send?access_token=e11f9c7d6f4c25da744ff90b429259e7bf29d7151cdccb864b97ecfba41cc56a";//测试

module.exports = async function (type, title, msg, btnList = [])
{
	if (type == "actionCard")
	{
		return dingdingActionCard(_dingdingUrl, title, msg, btnList)
	}
	else if (type == "feedCard")
	{
		return dingdingFeedCard(_dingdingUrl, title, msg, btnList)
	}
	else if (type == "markdown")
	{
		return dingdingMD(_dingdingUrl, title, msg, btnList)
	}

	return;
}

async function dingdingActionCard(url, title, msg, btnList = [])
{
	if (msg)
	{
		msg = " ### 【听君通知】" + title + "\n> " + msg.replace(/\n/g, " \n\n > ");

		var param = {
			actionCard: {
				title: title,
				text: msg,
				btnOrientation: "0",
				btns: btnList.map(v=>
				{
					return {
						title: v.title,
						actionURL: v.url
					}
				}),
			},
			msgtype: "actionCard"
		}
		await $.post(url, param);
	}
}

async function dingdingFeedCard(url, title, msg, btnList = [])
{
	if (msg)
	{
		msg = " ### 【听君通知】" + title + "\n> " + msg.replace(/\n/g, " \n\n > ");

		var param = {
			feedCard: {
				links: btnList.map(v=>
				{
					return {
						title: v.title,
						messageUrl: v.url
					}
				})
			},
			msgtype: "feedCard"
		}
		await $.post(url, param);
	}
}

async function dingdingLink(url, title, msg, btnList = [])
{
	if (msg)
	{
		msg = "听君通知】" + title + "-\n" + msg.replace(/\n/g, " \n\n");

		var param = {
			link: {
				title: title,
				text: msg,
				messageUrl: btnList[0].url
			},
			msgtype: "link",
			at: {
				atMobiles: ["18658110520", "18120588802", "15757117946"],
				isAtAll: false
			}
		}
		await $.post(url, param);
	}
}

async function dingdingMD(url, title, msg, btnList = [])
{
	if (msg)
	{
		msg = " ### 【听君通知】" + title + "\n> " + msg.replace(/\n/g, " \n\n > ") + "\n\n";
		msg += `[${btnList[0].title}](${btnList[0].url})`;

		var param = {
			markdown: {
				title: title,
				text: msg,
			},
			msgtype: "markdown",
			at: {
				isAtAll: true
			}
		}
		await $.post(url, param);
	}
}

//[{
//	title: "查看完整bug日志",
//	actionURL: "https://tweb.tingjunapp.com/.dev-bug-log/index.html?time=" + Date.now()
//}]